<template>
    <div class="container">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                    :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div v-show="showSearch" class="search">
                <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="68px">
                    <el-form-item label="城市名称" prop="addressName">
                        <el-input v-model="queryParams.addressName" clearable placeholder="请输入城市名称"
                                  style="width: 240px" @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="父Id" prop="parentId">
                        <el-input v-model="queryParams.parentId" clearable placeholder="请输入父Id" style="width: 240px"
                                  @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </transition>

        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['demo:tree:add']" icon="Plus" plain type="primary" @click="handleAdd()">
                            新增
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button icon="Sort" plain type="info" @click="handleToggleExpandAll">展开/折叠</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>
            <el-table
                ref="treeTableRef"
                v-loading="loading"
                :data="treeList"
                :default-expand-all="isExpandAll"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                row-key="addressId"
            >
                <el-table-column label="城市名称" prop="addressName" />
                <el-table-column align="center" label="父Id" prop="parentId" />
                <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
                    <template #default="scope">
                        <el-tooltip content="修改" placement="top">
                            <el-button v-hasPermi="['demo:tree:edit']" icon="Edit" link type="primary"
                                       @click="handleUpdate(scope.row)" />
                        </el-tooltip>
                        <el-tooltip content="新增" placement="top">
                            <el-button v-hasPermi="['demo:tree:add']" icon="Plus" link type="primary"
                                       @click="handleAdd(scope.row)" />
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button v-hasPermi="['demo:tree:remove']" icon="Delete" link type="primary"
                                       @click="handleDelete(scope.row)" />
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加或修改树表展示对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="500px">
            <el-form ref="treeFormRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="城市名称" prop="addressName">
                    <el-input v-model="form.addressName" placeholder="请输入城市名称" />
                </el-form-item>
                <el-form-item label="父Id" prop="parentId">
                    <el-tree-select
                        v-model="form.parentId"
                        :data="treeOptions"
                        :props="{ value: 'addressId', label: 'addressName', children: 'children' }"
                        :render-after-expand="false"
                        check-strictly
                        filterable
                        placeholder="请选择父Id"
                        value-key="addressId"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" name="Tree" setup>
import { listTree, getTree, delTree, addTree, updateTree } from "@/api/demo/tree";
import { TreeVO, TreeQuery, TreeForm } from "@/api/demo/tree/types";

type TreeOption = {
    addressId: number;
    addressName: string;
    children?: TreeOption[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;


const treeList = ref<TreeVO[]>([]);
const treeOptions = ref<TreeOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const treeFormRef = ref<ElFormInstance>();
const treeTableRef = ref<ElTableInstance>();

const dialog = reactive<DialogOption>({
    visible: false,
    title: "",
});


const initFormData: TreeForm = {
    addressId: undefined, addressName: undefined, parentId: undefined,
};

const data = reactive<PageData<TreeForm, TreeQuery>>({
    form: { ...initFormData },
    queryParams: {
        addressName: undefined,
        parentId: undefined,
        params: {},
    },
    rules: {},
});

const { queryParams, form, rules } = toRefs(data);

/** 查询树表展示列表 */
const getList = async () => {
    loading.value = true;
    const res = await listTree(queryParams.value);
    const data = proxy?.handleTree<TreeVO>(res.data, "addressId", "parentId");
    if (data) {
        treeList.value = data;
        loading.value = false;
    }
};

/** 查询树表展示下拉树结构 */
const getTreeselect = async () => {
    const res = await listTree();
    treeOptions.value = [];
    const data: TreeOption = { addressId: 0, addressName: "顶级节点", children: [] };
    data.children = proxy?.handleTree<TreeOption>(res.data, "addressId", "parentId");
    treeOptions.value.push(data);
};

// 取消按钮
const cancel = () => {
    reset();
    dialog.visible = false;
};

// 表单重置
const reset = () => {
    form.value = { ...initFormData };
    treeFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
    getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row?: TreeVO) => {
    reset();
    getTreeselect();
    if (row != null && row.addressId) {
        form.value.parentId = row.addressId;
    } else {
        form.value.parentId = 0;
    }
    dialog.visible = true;
    dialog.title = "添加树表展示";
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
    isExpandAll.value = !isExpandAll.value;
    toggleExpandAll(treeList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: TreeVO[], status: boolean) => {
    data.forEach((item) => {
        treeTableRef.value?.toggleRowExpansion(item, status);
        if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
    });
};

/** 修改按钮操作 */
const handleUpdate = async (row: TreeVO) => {
    reset();
    await getTreeselect();
    if (row != null) {
        form.value.parentId = row.parentId;
    }
    const res = await getTree(row.addressId);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改树表展示";
};

/** 提交按钮 */
const submitForm = () => {
    treeFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.addressId) {
                await updateTree(form.value).finally(() => buttonLoading.value = false);
            } else {
                await addTree(form.value).finally(() => buttonLoading.value = false);
            }
            proxy?.$modal.msgSuccess("操作成功");
            dialog.visible = false;
            getList();
        }
    });
};

/** 删除按钮操作 */
const handleDelete = async (row: TreeVO) => {
    await proxy?.$modal.confirm("是否确认删除树表展示编号为\"" + row.addressId + "\"的数据项？");
    loading.value = true;
    await delTree(row.addressId).finally(() => loading.value = false);
    await getList();
    proxy?.$modal.msgSuccess("删除成功");
};

onMounted(() => {
    getList();
});
</script>
